﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BaseHuman : MonoBehaviour
{
    //[Header("是否正在移动")]
    public bool isMoving;
    public Vector3 targetPos;
    public float speed;
    public Animator animator;

    // 聊天气泡挂载点
    [SerializeField] private Transform BubbleTrans;
    private void Awake()
    {
        ChatEventHub.I.OnChatMsg += OnChatMsg;
    }

    public string ClientID;


    // 有聊天消息事件
    private void OnChatMsg(string clientID, string msg)
    {
        if (clientID == ClientID)
            ShowChat(msg);
    }

    private ChatBubble curBubble;

    // 显示消息内容
    private void ShowChat(string msg)
    {
        if (curBubble != null)
            Destroy(curBubble.gameObject);

        var go = Resources.Load<GameObject>("ChatBubble");
        curBubble = Instantiate(go, BubbleTrans).GetComponent<ChatBubble>();
        curBubble.ShowChat(msg);
    }

    private void OnDestroy()
    {
        ChatEventHub.I.OnChatMsg -= OnChatMsg;
    }
    public void MoveTo(Vector3 target)
    {
        targetPos = target;
        isMoving = true;
        animator.SetInteger("State", 1);
    }

    private void MoveUpdate()
    {
        if (isMoving)
        {
            Vector3 pos = transform.position;
            transform.position = Vector3.MoveTowards(pos, targetPos, speed * Time.deltaTime);
            transform.LookAt(targetPos);

            if (Vector3.Distance(pos,targetPos)<0.05f)
            {
                isMoving = false;
                animator.SetInteger("State", 0);
            }
        }
    }
    // Start is called before the first frame update
    public void Start()
    {
        
    }

    // Update is called once per frame
    public void Update()
    {
        MoveUpdate();
    }
}
